package com.yxr.affairs.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;

import android.graphics.Color;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.thoughtworks.xstream.XStream;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.transformer.AccordionTransformer;
import com.yxr.affairs.BcActivity;
import com.yxr.affairs.DtActivity;
import com.yxr.affairs.IncludeActivity;
import com.yxr.affairs.InformActivity;
import com.yxr.affairs.LoginActicity1;
import com.yxr.affairs.MainActivity;
import com.yxr.affairs.QfActivity;
import com.yxr.affairs.R;
import com.yxr.affairs.XinActivity;
import com.yxr.affairs.YjActivity;
import com.yxr.affairs.api.Constans1;
import com.yxr.affairs.api.model.HomeResultEntity;
import com.yxr.affairs.api.tool.HomeGetApi;
import com.yxr.affairs.base.BaseFragment;
import com.yxr.affairs.home.Data;
import com.yxr.affairs.home.Param1;
import com.yxr.affairs.home.Storeditem;
import com.yxr.affairs.utils.GlideImageLoader;
import com.yxr.affairs.utils.UserInfo1;
import com.yxr.affairs.utils.Utils;
import com.yxr.affairs.xtem.EncodeXstream;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.Unbinder;


public class HomeFragment extends BaseFragment {

    @BindView(R.id.share_qq_id)
    ImageView shareQqId;
    @BindView(R.id.share_winxin_id)
    ImageView shareWinxinId;
    @BindView(R.id.share_friends_id)
    ImageView shareFriendsId;
    @BindView(R.id.activit_xinxi)
    ImageView activitXinxi;
    @BindView(R.id.activit_yiji)
    ImageView activitYiji;
    @BindView(R.id.activit_gengduo)
    ImageView activitGengduo;

    @BindView(R.id.rv_invest1)
    RecyclerView rvInvest1;

    private MainActivity mAActivity;



    private static float scale = 0;
    //W H proportion
    private static final int IMGW = 750;
    private static final int IMGH = 400;
    private static int widthPix = 0;
    private static int imgH = 0;
    ProgressDialog xh_pDialog;

    @BindView(R.id.banner)
    Banner bannerView;

    private HomeResultEntity mHomes;
    private   String Honst;
    private  String  time;
    private  int i=5;

    private ArrayList<ImageView> imageList;
   private MessageAdapter adapter;
   private ArrayList<Storeditem> storeditems =new ArrayList<>() ;
    private boolean isLaunch = false;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initViews() {

        if(!UserInfo1.isLogin()){

            Intent intent = new Intent();
            //SoilsenerActivity.class为想要跳转的Activity
            intent.setClass(getActivity(), LoginActicity1.class);
            startActivity(intent);
        }
        if (getActivity() instanceof MainActivity) {
            mAActivity = (MainActivity) getActivity();
        }

        if (widthPix == 0 || scale == 0) {
            DisplayMetrics metric = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
            widthPix = metric.widthPixels;
            scale = metric.density;
        }
        if (imgH == 0) {
            imgH = (widthPix * IMGH) / IMGW;
        }

        ViewGroup.LayoutParams params = bannerView.getLayoutParams();
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        params.height = imgH;
        bannerView.setLayoutParams(params);

        shareQqId.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if(!UserInfo1.isLogin()){

                    Intent intent = new Intent();
                    //SoilsenerActivity.class为想要跳转的Activity
                    intent.setClass(getActivity(), LoginActicity1.class);
                    startActivity(intent);
                }else {
                    Intent intent = new Intent();
                    //SoilsenerActivity.class为想要跳转的Activity
                    intent.setClass(getActivity(), DtActivity.class);
                    startActivity(intent);
                }


            }
        });
        shareWinxinId.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(!UserInfo1.isLogin()){

                    Intent intent = new Intent();
                    //SoilsenerActivity.class为想要跳转的Activity
                    intent.setClass(getActivity(), LoginActicity1.class);
                    startActivity(intent);
                }else {
                    Intent intent = new Intent();
                    //SoilsenerActivity.class为想要跳转的Activity
                    intent.setClass(getActivity(), IncludeActivity.class);
                    startActivity(intent);
                }


            }
        });
        shareFriendsId.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(!UserInfo1.isLogin()){

                    Intent intent = new Intent();
                    //SoilsenerActivity.class为想要跳转的Activity
                    intent.setClass(getActivity(), LoginActicity1.class);
                    startActivity(intent);
                }else{

                    Intent intent = new Intent();
                    //SoilsenerActivity.class为想要跳转的Activity
                    intent.setClass(getActivity(), XinActivity.class);
                    startActivity(intent);
                }


            }
        });
        activitXinxi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(!UserInfo1.isLogin()){

                    Intent intent = new Intent();
                    //SoilsenerActivity.class为想要跳转的Activity
                    intent.setClass(getActivity(), LoginActicity1.class);
                    startActivity(intent);
                }else {
                    Intent intent = new Intent();
                    //SoilsenerActivity.class为想要跳转的Activity
                    intent.setClass(getActivity(), BcActivity.class);
                    startActivity(intent);
                }
            }
        });
        activitYiji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(!UserInfo1.isLogin()){

                    Intent intent = new Intent();
                    //SoilsenerActivity.class为想要跳转的Activity
                    intent.setClass(getActivity(), LoginActicity1.class);
                    startActivity(intent);
                }else {
                    Intent intent = new Intent();
                    //SoilsenerActivity.class为想要跳转的Activity
                    intent.setClass(getActivity(), YjActivity.class);
                    startActivity(intent);
                }
            }
        });
        activitGengduo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!UserInfo1.isLogin()){

                    Intent intent = new Intent();
                    //SoilsenerActivity.class为想要跳转的Activity
                    intent.setClass(getActivity(), LoginActicity1.class);
                    startActivity(intent);
                }else {
                    Intent intent = new Intent();
                    //SoilsenerActivity.class为想要跳转的Activity
                    intent.setClass(getActivity(), InformActivity.class);
                    startActivity(intent);
                }


            }
        });

        loadData();


        if (!Utils.isNetworkConnected(mContext)) {
                Toast.makeText(mContext, getString(R.string.network_hint), Toast.LENGTH_SHORT).show();
                return;
            }


        if(!UserInfo1.isLogin()){

         /*   QueryAddressTask queryAddressTask = new QueryAddressTask();
            queryAddressTask.execute(Honst, time,  i+"");*/
            adapter  = new MessageAdapter(mContext, storeditems);
        /*rvInvest1.setLayoutManager(new LinearLayoutManager(mContext));
        rvInvest1.setAdapter(adapter);*/
            rvInvest1.setLayoutManager(new LinearLayoutManager(mContext));
            rvInvest1.setAdapter(adapter);
        }

         //   rvInvest1.setGroupIndicator(null);



    }

  class QueryAddressTask extends AsyncTask<String, Integer, String> {
      @Override
      protected void onPreExecute() {
          xh_pDialog = new ProgressDialog(mContext);

          // 设置进度条风格，风格为圆形，旋转的
          xh_pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
          xh_pDialog.setTitle("正在加载，请稍等");
          xh_pDialog.setIndeterminate(false);

          // 设置ProgressDialog 是否可以按退回键取消
          xh_pDialog.setCancelable(true);

          // 让ProgressDialog显示
          xh_pDialog.show();

      }
      protected String doInBackground(String... params) {
          // 查询手机号码（段）信息*/
          String    result = null;

          try {
              result = getData(params[0]);


          } catch (Exception e) {

              e.printStackTrace();
          }
          //将结果返回给onPostExecute方法

          Log.e("ADDADADggg",result);
          return result;
      }



      @Override
    //此方法可以在主线程改变UI
    protected void onPostExecute(String result) {
        // 将WebService返回的结果显示在TextView中

        xh_pDialog.dismiss();
       if (result != null) {
            XStream xStream1 = new EncodeXstream("1.0", "gb2312");
            xStream1.alias("result", Data.class);
            xStream1.useAttributeFor(Param1.class, "size");
            xStream1.addImplicitCollection(Param1.class, "storeditems");
            xStream1.alias("storeditem", Storeditem.class);
            Data data1 = (Data) xStream1.fromXML(result);

            Log.e("TAG11", "status: " + data1.getStatus());
            Log.e("TAG11", "errorinfo: " + data1.getErrorinfo());
            Log.e("TAG11","successinfo"+data1.getSuccessinfo());
            Log.e("TAG11", "param1 size: " + data1.getSuccessinfo().getParam1().getSize());

            Log.e("aadasf",result);

            try {

                storeditems.clear();
                storeditems.addAll((ArrayList<Storeditem>) data1.getSuccessinfo().getParam1().getStoreditems());
                adapter.notifyDataSetChanged();



            } catch (Exception e) {

                e.printStackTrace();
            }

        }


}
}

    private String getData(String param){
        String    result = null;
        String WSDL_URI = Constans1.getData(mContext);//wsdl 的uri
        Log.d("FAFAFF",WSDL_URI);
        String namespace = "urn:HyWebServerIntf-IHyWebServer";//namespace
        String methodName = "HyWebServiceIntfMethod";//要调用的方法名称

        SoapObject request = new SoapObject(namespace, methodName);

        String de = "<hywebserviceroot>" +
                "<funname>GetMbUserFunction</funname>" +
                "<hospitalid>H1504080000001</hospitalid>" +
                "    <key>21644BE1DD5915CDC8CF09E4607789288E3322A0C07D9E9108B89A14FF01CC6644B27E6616F4A17C390445BCA04922B2E7E923B871841BD10C7E5E08B0FDE522</key>" +
                "    <deviceid>001</deviceid>" +
                "    <usercode>9999</usercode>" +
                "    <userpwd>123456</userpwd>" +
                "    <version>5.0</version>" +
                "    <params>" +
                "     <param1><sFunName>GetSYXX</sFunName></param1>" +
                "     <param2></param2>" +
                "    </params>" +
                "</hywebserviceroot>";

        request.addProperty("aXml", de);
        //创建SoapSerializationEnvelope 对象，同时指定soap版本号(之前在wsdl中看到的)

        try {
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11);
            envelope.bodyOut = request;//由于是发送请求，所以是设置bodyOut
            envelope.dotNet = true;//由于是.net开发的webservice，所以这里要设置为true
            HttpTransportSE httpTransportSE = new HttpTransportSE(WSDL_URI);
            httpTransportSE.debug = false;
            httpTransportSE.call("urn:HyWebServerIntf-IHyWebServer#HyWebServiceIntfMethod", envelope);//调用

            // 获取服务器响应返回的SOAP消息
            SoapObject object = (SoapObject) envelope.bodyIn;
            result = object.getProperty(0).toString();
            //     Log.e("DSDSDS", result);
            return result;

        } catch (Exception e) {
            Log.e("TAG", "getData: "+e );
        }
        return result;

    }


   /* private  class  MessageAdapter extends BaseExpandableListAdapter {


        private Context context;
        private ArrayList<Storeditem> storeditems;

        public MessageAdapter(Context context, ArrayList<Storeditem> dataLists) {
            this.context = context;
            this.storeditems = dataLists;
        }

        public Object getChild(int groupPosition, int childPosition) {
            return storeditems.get(groupPosition);
        }

        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        public int getChildrenCount(int groupPosition) {
            return 1;
        }

        public View getChildView(int groupPosition, int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {

            ViewHolder1 viewHolder1;
            if (convertView == null) {
                viewHolder1 = new ViewHolder1();
                convertView = View.inflate(context, R.layout.activity_reaws_item2, null);
                viewHolder1.tv = (TextView) convertView.findViewById(R.id.activity_home2);


                convertView.setTag(viewHolder1);
            } else {
                viewHolder1 = (ViewHolder1) convertView.getTag();
            }
            viewHolder1.tv.setText(storeditems.get(groupPosition).getsFSXX());

            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return false;
        }


        public Object getGroup(int groupPosition) {
            return storeditems.get(groupPosition);
        }

        public int getGroupCount() {
            return storeditems.size();
        }

        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        public View getGroupView(int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent) {

            ViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = View.inflate(context, R.layout.activity_reaws_item1, null);
                viewHolder.tv = (TextView) convertView.findViewById(R.id.activity_home);
                viewHolder.tv1 = (TextView) convertView.findViewById(R.id.activity_home1);

                convertView.setTag(viewHolder);
                viewHolder.tv.setText(storeditems.get(groupPosition).getsXXLX());
                viewHolder.tv1.setText("发布日期："+storeditems.get(groupPosition).getdFSSJ());
                }
            return convertView;
        }


        class ViewHolder {
            TextView tv;
            TextView tv1;

        }

        class ViewHolder1 {
            TextView tv;
            TextView tv1;
            TextView tv2;
        }
    }*/
    public  class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder>{


        private ArrayList<Storeditem>  storeditems;
        private Context mContext;
        public MessageAdapter( Context context, ArrayList<Storeditem> dataLists){

            mContext=context;
            this.storeditems=dataLists;
        }

        private Context getContext() {
            return mContext;
        }

        @Override
        public MessageAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            Context context = parent.getContext();
            LayoutInflater inflater = LayoutInflater.from(context);

            View contactView = inflater.inflate(R.layout.activity_ahome, parent, false);

            MessageAdapter.ViewHolder viewHolder = new MessageAdapter.ViewHolder(contactView);
            return viewHolder;

        }

        @Override
        public void onBindViewHolder(final MessageAdapter.ViewHolder holder, final int position) {



            holder.TextView1.setText(storeditems.get(position).getsXXLX());
            holder.TextView2.setText("发布日期："+storeditems.get(position).getdFSSJ());

            }

        @Override
        public int getItemCount() {
            return storeditems.size();
        }
        public class ViewHolder extends RecyclerView.ViewHolder {


            public TextView TextView1;
            public TextView TextView2;



            public ViewHolder(View itemView) {
                super(itemView);

                TextView1 = (TextView)itemView.findViewById(R.id.activity_home);
                TextView2 = (TextView)itemView.findViewById(R.id.activity_home1);

            }
        }
    }
    @Override
    protected void updateViews(boolean isRefresh) {
       /* if (!isRefresh) {
            *//*finishRefresh();*//*
            showLoading();
        }*/

      //  getIndexData();
    }


    @Override
    protected void onError_(Throwable e) {
        showNetError();
    }

    @Override
    protected void onCancel_() {

    }

    /*private void loadData() {
        //banenr图
        List<HomeResultEntity.DataBean.BannerBean> banner = mHomes.getData().getBanner();
        List<String> images = new ArrayList<>();
        for (int i = 0; i < banner.size(); i++) {
            images.add(banner.get(i).getPic());
        }
        bannerView.setImages(images)
//                .setBannerTitles(App.titles)//标题
                .setBannerAnimation(AccordionTransformer.class)//动画
                .setIndicatorGravity(BannerConfig.RIGHT)//指示器位置
//                .setBannerStyle(BannerConfig.CIRCLE_INDICATOR)//指示器样式
                .setDelayTime(3000)//延迟4S
                .setImageLoader(new GlideImageLoader())
                .setOnBannerListener(this)
                .start();

    }*/
    private void loadData() {

        List<Integer> list = new ArrayList<>();
        list.add(R.mipmap.banana);
        list.add(R.mipmap.banana);
        list.add(R.mipmap.banana);

            bannerView.setImages(list)
//                .setBannerTitles(App.titles)//标题
                    .setBannerAnimation(AccordionTransformer.class)//动画
                    .setIndicatorGravity(BannerConfig.RIGHT)//指示器位置
//                .setBannerStyle(BannerConfig.CIRCLE_INDICATOR)//指示器样式
                    .setDelayTime(3000)//延迟4S
                    .setImageLoader(new GlideImageLoader())
                    .start();


    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }
}
